﻿@{
    ViewData["Title"] = "Home Page";
}

<h2>CORS example</h2>
<p>This page sends requests to http://localhost:5111 (api.shopping.com) to fetch a list of products. Press <code>F12</code> to view the full log, and failed CORS messages</p>

<h3>Products:</h3>
<ul id="products"></ul>

<h3>Log:</h3>
<div id="debugDiv" style="{height: 200px; width: 500px; border: 1px solid #333; overflow:scroll;}"></div>

@section Scripts
{
    <script>
        var api = 'http://localhost:5111/api/products';
        redirectLogToDiv();
        console.log('Loading home page...');

        console.log('Preparing request...');
        

        var xhr = new XMLHttpRequest();
        xhr.open('get', api);
        xhr.addEventListener("progress", updateProgress);
        xhr.addEventListener("load", transferComplete);
        xhr.addEventListener("error", transferFailed);
        xhr.addEventListener("abort", transferCanceled);
        xhr.onload = onLoad;

        console.log('Sending request to ' + api + '...');
        xhr.send();

        function redirectLogToDiv() {
            if (typeof console != "undefined") {
                if (typeof console.log != 'undefined') {
                    console.olog = console.log;
                } else {
                    console.olog = function () { };
                }
            }

            console.log = function (message) {
                console.olog(message);
                $('#debugDiv').append('<p>' + message + '</p>');
            };
            console.error = console.debug = console.info = console.log
        }

        function onLoad(e) {
            var response = xhr.response;
            console.log('Recieved data: ' + response);
            var data = JSON.parse(response);
            var ul = document.getElementById('products');
            for (var i = 0; i < data.length; i++) {
                var li = document.createElement('li')
                li.textContent = data[i];
                ul.appendChild(li);
            }
            console.log('Request complete');
        }

        function updateProgress(oEvent) {
            if (oEvent.lengthComputable) {
                var percentComplete = oEvent.loaded / oEvent.total;
                console.log( percentComplete + "% complete...");
            } else {
                console.log("Request in progress...");
            }
        }

        function transferComplete(evt) {
            console.log("The transfer is complete.");
        }

        function transferFailed(evt) {
            console.log("An error occurred while loading the products.");
        }

        function transferCanceled(evt) {
            console.log("The transfer has been canceled by the user.");
        }

    </script>
}